from django.conf import settings
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework.mixins import (
    UpdateModelMixin,
    DestroyModelMixin,
    RetrieveModelMixin,
    ListModelMixin,
    CreateModelMixin,
)
from rest_framework import serializers
from .models import TestModel


##################
# testModelViewset
##################
class TestReqSerializers(serializers.ModelSerializer):
    class Meta:
        model = TestModel
        fields = "__all__"

    def update(self, instance, validated_data):
        print("serializers-update")
        validated_data["name"] = "chenhaifeng"
        return super().update(instance, validated_data)


class TestRespSerializers(serializers.ModelSerializer):
    class Meta:
        model = TestModel
        fields = "__all__"


class TestAppModelViewSet(GenericViewSet, UpdateModelMixin, ListModelMixin):
    queryset = TestModel.objects.all()
    serializer_class = TestReqSerializers
    resp_serializers_class = TestRespSerializers

    def update(self, request, *args, **kwargs):
        print("test-app-update")
        return super().update(request, *args, **kwargs)


######
# csv
######
from rest_framework_csv.renderers import CSVRenderer
from rest_framework.response import Response
from rest_framework.settings import api_settings


class CSVReqserializers(serializers.ModelSerializer):
    class Meta:
        model = TestModel
        fields = "__all__"


class MyUserRenderer(CSVRenderer):
    """
    方式1: 指定渲染器
        Response之后触发过滤
        只会显示header里的字段
    """

    header = ["msg", "name"]
    labels = {"msg": "消息", "name": "姓名"}
    filename = "test.csv"

    def render(self, data, media_type=None, renderer_context=..., writer_opts=None):
        """
        重写文件名
        """
        renderer_context["response"].headers[
            "Content-Disposition"
        ] = f'attachment; filename="{self.filename}"'
        return super().render(data, media_type, renderer_context, writer_opts)


class CSVModelViewSet(ModelViewSet):
    queryset = TestModel.objects.all()
    serializer_class = CSVReqserializers

    def retrieve(self, request, *args, **kwargs):
        test = self.get_queryset().first()
        return Response({"id": test.id, "msg": test.msg, "name": test.name})

    def get_renderers(self):
        render_classes = tuple(api_settings.DEFAULT_RENDERER_CLASSES)
        if hasattr(self, "action"):
            if self.action in (
                "list",
                "retrieve",
            ):
                render_classes = (MyUserRenderer,)
        return (render() for render in render_classes)

    # def get_renderer_context(self):
    #     """
    #     方式2: 重写渲染器内容
    #         Response后触发过滤
    #         只会显示header里的字段
    #     """
    #     context = super().get_renderer_context()
    #     context["header"] = (
    #         self.request.GET["fields"].split(",")
    #         if "fields" in self.request.GET
    #         else None
    #     )
    #     return context


########
# excet
########
from rest_framework.viewsets import ReadOnlyModelViewSet
from drf_excel.mixins import XLSXFileMixin
from drf_excel.renderers import XLSXRenderer
from datetime import datetime

class EXCELSerializers(serializers.Serializer):
    id = serializers.IntegerField()
    msg = serializers.CharField()
    name = serializers.CharField()
    created_at = serializers.DateTimeField()
    distance = serializers.DecimalField(max_digits=4, decimal_places=3)

    def get_created_at(self, instance):
        return datetime.strftime(instance["created_at"], "%Y-%m-%d %H:%M")


class EXCELModelViewSet(XLSXFileMixin, ReadOnlyModelViewSet):
    queryset = TestModel.objects.all()
    serializer_class = EXCELSerializers
    renderer_classes = (XLSXRenderer,)
    filename = "my_export.xlsx"
    column_header = {
        "titles": [
            "id",
            "消息",
            "姓名",
            "时间",
            "小数点"
        ],
        "column_width": [17, 30, 17, 17, 17],
        "height": 25,
        "style": {
            "fill": {
                "fill_type": "solid",
                "start_color": "FFFFFF", # 白色
            },
            "alignment": {
                "horizontal": "center",
                "vertical": "center",
                "wrapText": True,
                "shrink_to_fit": True,
            },
            "border_side": {
                "border_style": "thin",
                "color": "FF000000",
            },
            "font": {
                "name": "Arial",
                "size": 14,
                "bold": True,
                "color": "FF000000",
            },
        },
    }
    body = {
        "style": {
            "fill": {
                "fill_type": "solid",
                "start_color": "FFCCFFCC",
            },
            "alignment": {
                "horizontal": "center",
                "vertical": "center",
                "wrapText": True,
                "shrink_to_fit": True,
            },
            "border_side": {
                "border_style": "thin",
                "color": "FF000000",
            },
            "font": {
                "name": "Arial",
                "size": 14,
                "bold": False,
                "color": "FF000000",
            },
        },
        "height": 40,
    }
    # 时间格式化excel内部
    column_data_styles = { 
        "distance": {
            "alignment": {
                "horizontal": "right",
                "vertical": "top",
            },
            "format": "0.00E+00",
        },
        "created_at": {
            "format": "yyyy-dd-mm h:mm AM/PM",
        },
    }
    
    def list(self, request, *args, **kwargs):
        testes = self.get_queryset()
        ser = self.get_serializer(testes, many=True) # 必须要时间序列化器
        return Response(data=ser.data)
